//
//  ViewController.m
//  九宫格
//
//  Created by song on 15/1/5.
//  Copyright (c) 2015年 song. All rights reserved.
//

#import "ViewController.h"
#import "SJOApp.h"
#import "SJOAppview.h"



@interface ViewController ()

@property(nonatomic, strong) NSArray *apps;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    int pcount = 3;
    //这个应用的长宽
    CGFloat appW = 80;
    CGFloat appH =80;

    // 每个应用的 间隙的宽度
    CGFloat appMargin = (self.view.frame.size.width - pcount * appW )/ (pcount+1);
    
    NSBundle *mainbundle = [NSBundle mainBundle];
    for(int i =0 ;i<self.apps.count;i++)
    {
        int  x =  i% pcount ;   // 这个应用再第几列
        int y = i /pcount ;     // 应用再第几行
        CGFloat xpos =  appMargin * (x  +1)  + x * appW; // 计算 x 的坐标的 m+h|m+h|m+h|m+h  就知道了
        CGFloat ypos =  appMargin * (y  +1)  +y * appH;

        NSArray *objs = [mainbundle loadNibNamed:@"SJOAppview" owner:nil options:nil]; //加载xib 文件
        SJOAppview   *view = [objs lastObject];
        view.frame =  CGRectMake(xpos, ypos, appW, appH);
        view.app = self.apps[i];
        [self.view addSubview:view];
        
    }
    
    
    
    
    
}

-(NSArray *)apps
{
    if(_apps==nil)
    {
        NSMutableArray *appdata = [[NSMutableArray alloc]initWithCapacity:0];
        NSBundle *mainbundle = [NSBundle mainBundle];
        NSString *ppath =[mainbundle pathForResource:@"imagedata" ofType:@"plist"];
        NSArray *resouces =[NSArray arrayWithContentsOfFile:ppath];
        for(NSDictionary *dic in resouces)
        {
            SJOApp *app = [[SJOApp alloc]init];
            app.icon  = dic[@"icon"];
            app.name = dic[@"name"];
            [appdata addObject:app];
            
        }
        _apps = appdata;
    }
    return _apps;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
